// pages/wallet/wallet.js
import api from "../../utils/apis.js";
import message from "../../utils/message.js";
import util from "../../utils/util.js";

Page({
  /**
   * Page initial data
   */
  data: {
    coinName: "",
    balance: "",
    walletAddress: "",
    historyData: [],
    cashNotSure: "",
    totol: null
  },
  handleClick() {

    if (!wx.getStorageSync("userMobile")) {
      wx.redirectTo({
        url: "/pages/login/login?coinName=" +
          this.data.coinName +
          "&balance=" +
          this.data.balance +
          "&walletAddress=" +
          this.data.walletAddress
      })
    } else {
      wx.navigateTo({
        url: "/pages/cash/cash?coinName=" +
          this.data.coinName +
          "&balance=" +
          this.data.balance +
          "&walletAddress=" +
          this.data.walletAddress
      });
    }
  },
  /**
   * Lifecycle function--Called when page load
   */
  onLoad: function(options) {
    this.setData({
      coinName: options.coinName,
      balance: options.balance,
      walletAddress: options.walletAddress
    });

    let t = "";
    if (this.data.coinName == "STORJ") {
      t = "1";
    } else if (this.data.coinName == "FIL") {
      t = "4";
    } else if (this.data.coinName == "UT") {
      t = "3";
    } else if (this.data.coinName == "PLC") {
      t = "2";
    }

  },

  gainCoinList(type) {
    let self = this;

    // let param = {
    //   coinType: type
    // }

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });

    wx.request({
      url: api.shouyiListApi + "/" + type,
      method: "GET",
      // data: param,
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        console.log(res);
        if (res.statusCode == "200") {
          let data = res.data;

          data.forEach(element => {
            if (element.tradeType == "2") {
              element.tradeTypeName = "收益";
              element.showData = element.displayProfitAmount.toFixed(2);
              element.states = "收益到账";
            } else if (element.tradeType == "4") {
              element.tradeTypeName = "算力收益";
              element.states = "收益到账";
              element.showData = element.displayProfitAmount.toFixed(2);
            } else if (element.tradeType == "3") {
              element.tradeTypeName = "节点收益";
              element.states = "收益到账";
              element.showData = element.displayProfitAmount.toFixed(2);
            } else if (element.tradeType == 1) {
              element.tradeTypeName = "提现";
              element.states = "提现成功";
              element.showData = element.displayProfitAmount.toFixed(2);
            }
          });
          self.setData({
            historyData: data
          });
        } else {
          message.showInfo(
            res.data.message ? res.data.message : "网络连接异常"
          );
        }
      }
    });
  },
  gainCashList(t) {
    let self = this;

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: "加载中"
    });

    wx.request({
      url: api.cashNotSure,
      method: "GET",
      header: {
        Authorization: "Bearer " + token
      },
      success(res) {
        wx.hideLoading();
        console.log(res);
        if (res.statusCode == "200") {
          let data = res.data;
          let temp = [];
          data.forEach(element => {
            if (element.auditStatus == 0) {
              element.applyTime = self.time(element.applyTime);
              temp.push(element);
            }
          })
          let temp1 = [];
          let coinName = "";
          if (t == "1") {
            coinName = "Storj"
            temp.forEach(element => {
              if (element.coinType == 1) {
                element.applyTime = self.time(element.applyTime);
                temp1.push(element);
              }
            })

          } else if (t == '2') {
            coinName = "PLC"
            temp.forEach(element => {
              if (element.coinType == 2) {
                element.applyTime = self.time(element.applyTime);
                temp1.push(element);
              }
            })
          }
          let string="";
          console.log(temp1)
          if (temp1.length>0){
            string = "您目前有" + temp1.length + "笔的" + coinName + "提现，正在审核中:" + "      ";
            temp1.forEach(element => {
              string = string + "您于" + element.applyTime + "提现了" + element.applyAmount + "个" + coinName + ";    ";
            })
          }
          self.setData({
            cashNotSure: string,
            totol: temp.length
          })
        } else {
          message.showInfo(
            res.data.message ? res.data.message : "网络连接异常"
          );
        }
      }
    });
  },
  time(t) {
    let lenT = t.indexOf(".");
    let time1 = t.slice(0, lenT);
    let time2 = t.slice(lenT + 1, lenT + 10);
    return time1;
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady: function() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow: function() {
    let t = "";
    if (this.data.coinName == "STORJ") {
      t = "1";
    } else if (this.data.coinName == "FIL") {
      t = "4";
    } else if (this.data.coinName == "UT") {
      t = "3";
    } else if (this.data.coinName == "PLC") {
      t = "2";
    }
    this.gainCashList(t);
    this.gainCoinList(t);

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide: function() {},

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload: function() {},

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh: function() {},

  /**
   * Called when page reach bottom
   */
  onReachBottom: function() {},

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage: function() {},

  sendSmsAction: function () {
    let self = this;

    if (!self.data.phoneValue) {
      wx.showToast({
        title: '手机号不能为空',
        icon: '',
        image: '/images/logo/warning.png',
        duration: 2000
      })
      return
    }

    if (self.data.phoneValue.length != 11) {
      wx.showToast({
        title: '手机号不正确',
        icon: '',
        image: '/images/logo/warning.png',
        duration: 2000
      })
      return
    }

    let param = {
      mobile: self.data.phoneValue
    }

    wx.showLoading({
      title: '加载中',
    })

    wx.request({
      url: api.sendSmsCode,
      method: "POST",
      data: param,
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        wx.hideLoading()
        message.showSuccess('验证码已发送')
        if (res.statusCode == '200') {

          let temp = setInterval(() => {
            if (self.data.countNum == 0) {
              self.setData({
                countNum: 60
              })

              self.setData({
                countText: '发送验证码'
              })

              if (self.data.intervalNum != null && self.data.intervalNum != undefined) {
                clearInterval(self.data.intervalNum)
              }
            } else {
              let num2 = self.data.countNum
              num2 -= 1
              self.setData({
                countNum: num2
              })
            }
          }, 1000)

          self.setData({
            intervalNum: temp
          })
        } else {
          message.showInfo(res.data.message ? res.data.message : '网络连接异常')
        }
      }
    });
  },

  bindPhoneAction() {
    let self = this

    if (!self.data.phoneValue) {
      wx.showToast({
        title: '手机号不能为空',
        icon: '',
        image: '/images/logo/warning.png',
        duration: 2000
      })
      return
    }

    if (self.data.phoneValue.length != 11) {
      wx.showToast({
        title: '手机号不正确',
        icon: '',
        image: '/images/logo/warning.png',
        duration: 2000
      })
      return
    }

    if (!self.data.verifyCode) {
      wx.showToast({
        title: '验证码不能为空',
        icon: '',
        image: '/images/logo/warning.png',
        duration: 2000
      })
      return
    }

    let param = {
      smsCode: self.data.verifyCode,
      mobile: self.data.phoneValue,
    }

    let token = wx.getStorageSync("authorization");

    wx.showLoading({
      title: '加载中',
    })

    wx.request({
      url: api.bindPhoneApi,
      method: "POST",
      data: param,
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "authorization": "Bearer " + token
      },
      success(res) {
        wx.hideLoading()
        message.showSuccess('绑定手机号成功')
        console.log(res)
        if (res.statusCode == '200') {
          let token = res.data.id_token;

          try {
            wx.setStorageSync("authorization", token);
            console.log('刷新了token')
          } catch (e) {
            console.log(e);
          }


          wx.redirectTo({
            url: '/pages/index/index',
          })
        } else {
          message.showInfo(res.data.message ? res.data.message : '网络连接异常')
        }
      }
    });
  },

  ensureAction() {
    this.setData({
      isKnowledegShow: false
    })
  },

  cancelAction() {
    this.setData({
      isLoginShow: false
    })
  }
});